import express from 'express';
import morgan from 'morgan';
const app = express();
import { readdirSync } from 'fs';
import { join } from 'path';
app.use(morgan('combined'));

const mock_dir = 'mock_router';
const files = readdirSync(mock_dir);
for (const file of files) {
  let mock = require(join(__dirname, mock_dir, file));
  for (const key in mock.default) {
    let list1 = key.split(' ');
    let method = 'get';
    let api = '';
    if (list1.length === 1) {
      method = 'get';
      api = key;
    } else {
      method = list1[0].toLowerCase();
      api = list1[1];
    }
    if (api.indexOf('api') === -1) continue;
    console.log(`api:${method} ${api}`);
    let modules = mock.default[key];
    if (typeof modules === 'function') {
      app[method](api, modules);
    } else {
      app[method](api, function (req, res) {
        return res.json(modules);
      });
    }
  }
}

app.use(function (err, req, res, next) {
  if (typeof err === 'string') {
    return res.json({ result: -1, error: err });
  }
  let tip = `App Error：${req.method} ${req.originalUrl} ${JSON.stringify(req.body || '-')} ${
    req.from
  } ${req.system_version || '-'} ${req.app_version || '-'} ${req.uuid}`;
  console.log(tip, err.message);
  res.json({ result: -1, error: err.message || err });
});

//处理未识别的请求,未发现请求
app.use('/', function (req, res) {
  console.log(
    'Cannot ' + req.method + ' ' + req.originalUrl,
    JSON.stringify(req.query),
    JSON.stringify(req.body),
    req.uuid,
  );
  res.json({ result: 404, error: 'Cannot ' + req.method + ' ' + req.originalUrl });
});

let port = 8002;
app.listen(port, function () {
  console.log(`Example app listening at http://127.0.0.1:${port}`);
});
